﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Marbles.Core.Content.Sites;
using System.IO;
using Marbles.Core.Connectors;

namespace Marbles.Core.Content.Templates
{
    public class TemplateCollection : ICollection<TemplateFile>
    {

        public TemplateFile this[int index] { get { return items[index]; } }

        private SiteDefinition _site = null;
        private List<TemplateFile> items = null;

        public TemplateCollection(SiteDefinition Site, bool loadcontent)
        {
            items = new List<TemplateFile>();
            _site = Site;
            Load(loadcontent);
        }

        public TemplateCollection(bool loadcontent)
        {
            items = new List<TemplateFile>();
            _site = SiteDefinition.GetCurrent();
            Load(loadcontent);
        }

        private void Load(bool loadcontent)
        {
            items.Clear();
            foreach (string filename in Directory.GetFiles(_site.ApplicationTemplateDirectory, "*.master"))
            {
                items.Add(new TemplateFile(new FileInfo(filename), loadcontent, _site));
            }
            items.Sort();
        }

        public void Add(TemplateFile item)
        {
            items.Add(item);
        }

        public void Clear()
        {
            items.Clear();
        }

        public bool Contains(TemplateFile item)
        {
            return items.Contains(item);
        }

        public void CopyTo(TemplateFile[] array, int arrayIndex)
        {
            items.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return items.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(TemplateFile item)
        {
            return items.Remove(item);
        }

        public IEnumerator<TemplateFile> GetEnumerator()
        {
            return items.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return items.GetEnumerator();
        }

        public static TemplateFile Create(SiteDefinition site, string name)
        {
            string filename = Path.Combine(site.ApplicationTemplateDirectory, name + ".master");
            FileInfo info = new FileInfo(filename);
            if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); }
            StreamWriter sw = new StreamWriter(filename);
            sw.Write(Template.DefaultTemplateValue);
            sw.Flush();
            sw.Close();
            return new TemplateFile(new FileInfo(filename), true, site);
        }
    }

    public class TemplateFile : IComparable<TemplateFile>
    {
        public string Name { get { return _name; } }
        public string Filename { get { return _filename; } }
        public string FullName { get { return _fullname; } }
        public string Value { get { return _value; } set { _value = value; } }

        private string _filename = string.Empty;
        private string _fullname = string.Empty;
        private string _name = string.Empty;
        private string _value = string.Empty;
        private SiteDefinition _site = null;

        public TemplateFile(FileInfo info, bool loadcontent, SiteDefinition site)
        {
            _filename = info.Name;
            _fullname = info.FullName;
            _name = Path.GetFileNameWithoutExtension(info.FullName);
            _value = string.Empty;
            _site = site;
            if (loadcontent) { Load(); }
        }

        public TemplateFile(string filename, bool loadcontent, SiteDefinition site)
            : this(new FileInfo(filename), loadcontent, site)
        {
        }

        public TemplateFile(SiteDefinition site, string name, bool loadcontent)
            : this(Path.Combine(site.ApplicationTemplateDirectory, name + ".master"), loadcontent, site)
        {
        }

        public void Load()
        {

            StreamReader sr = new StreamReader(_fullname);
            _value = sr.ReadToEnd();
            sr.Close();
        }

        public void SaveAs(string name)
        {
            FileInfo info = new FileInfo(_fullname);
            if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); }

            string filename = Path.Combine(_site.ApplicationTemplateDirectory, name + ".master");

            Delete();
            UpdateTemplateReferences(_name, name);
            _name = name;
            _fullname = filename;
            StreamWriter sw = new StreamWriter(filename);
            sw.Write(_value);
            sw.Flush();
            sw.Close();
        }

        private void UpdateTemplateReferences(string oldname, string newname)
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("UPDATE pages SET templatename = @newname WHERE siteid = @siteid AND templatename = @oldname");
            cmd.AddParameter("@newname", newname);
            cmd.AddParameter("@oldname", oldname);
            cmd.AddParameter("@siteid", _site.SiteId);
            dbc.ExecuteCommand(cmd);
        }

        public void Save()
        {
            FileInfo info = new FileInfo(_fullname);
            if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); }

            Delete();
            StreamWriter sw = new StreamWriter(_fullname);
            sw.Write(_value);
            sw.Flush();
            sw.Close();
        }

        public void Delete()
        {
            if (File.Exists(_fullname)) { File.Delete(_fullname); }
        }


        public int CompareTo(TemplateFile other)
        {
            return _name.CompareTo(other.Name);
        }
    }
}
